﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Apps.Common;
using Apps.IBLL;
using Apps.Models.Sys;
using Microsoft.Practices.Unity;
using Apps.IBLL.Flow;
using Apps.Models.Flow;
using System.Text;
using Apps.BLL.Flow;
using Apps.Web.Core;
using Apps.Models.Enum;
using Apps.Locale;
using Apps.IBLL.Sys;
using System.Linq.Expressions;
using Apps.Models;
using Apps.IBLL.LMS;
using Wantn.FIS.Enum;

namespace Apps.Web.Areas.Flow.Controllers
{
    public class ExamineController : BaseController
    {
        [Dependency]
        public ISysUserBLL userBLL { get; set; }
        [Dependency]
        public IFlow_TypeBLL m_BLL { get; set; }
        [Dependency]
        public IFlow_FormBLL formBLL { get; set; }
        [Dependency]
        public IFlow_FormAttrBLL formAttrBLL { get; set; }
        [Dependency]
        public IFlow_FormContentBLL formContentBLL { get; set; }
        [Dependency]
        public IFlow_StepBLL stepBLL { get; set; }
        [Dependency]
        public IFlow_StepRuleBLL stepRuleBLL { get; set; }
        [Dependency]
        public IFlow_FormContentStepCheckBLL stepCheckBLL { get; set; }
        [Dependency]
        public IFlow_FormContentStepCheckStateBLL stepCheckStateBLL { get; set; }
        [Dependency]
        public IFlow_ExternalBLL externalBLL { get; set; }

        [Dependency]
        public ILMS_TESTDATA_AUDITBLL m_testdataBLL { get; set; }

        ValidationErrors errors = new ValidationErrors();

        [SupportFilter]
        //public ActionResult Index()
        //{
        //    List<Flow_FormContentModel> list = formContentBLL.GetMyExaminetListByUserId(ref setNoPagerAscById, "", GetUserId()); 
        //    foreach (var model in list)
        //    { 
        //        model.CurrentState = formContentBLL.GetCurrentFormState(model);
        //    }
        //    FlowStateCountModel stateModel = new FlowStateCountModel();
        //    stateModel.requestCount = list.Count();
        //    stateModel.passCount = list.Where(a => a.CurrentState == (int)FlowStateEnum.Pass).Count();
        //    stateModel.rejectCount = list.Where(a => a.CurrentState == (int)FlowStateEnum.Reject).Count();
        //    stateModel.processCount = list.Where(a => a.CurrentState == (int)FlowStateEnum.Progress).Count();
        //    //stateModel.closedCount = list.Where(a => a.TimeOut < DateTime.Now).Count();
        //    stateModel.closedCount = list.Where(a => a.CurrentState == (int)FlowStateEnum.Closed).Count();
        //    return View(stateModel);
        //}
        public ActionResult Index()
        { 
            var pager = new GridPager()
            {
                page = 1,
                rows = 10000,
                sort = "ID",
                order = "asc"
            };
            FlowStateCountModel stateModel = new FlowStateCountModel();
            var list = formContentBLL.GetMyExaminetListByUserId(ref pager, "", GetUserId(), 0);
            stateModel.requestCount = list == null ? 0 : list.Count;
            list = formContentBLL.GetMyExaminetListByUserId(ref pager, "", GetUserId(), 2);
            stateModel.passCount = list == null ? 0 : list.Count;
            list = formContentBLL.GetMyExaminetListByUserId(ref pager, "", GetUserId(), 3);
            stateModel.rejectCount = list == null ? 0 : list.Count;
            list = formContentBLL.GetMyExaminetListByUserId(ref pager, "", GetUserId(), 1);
            stateModel.processCount = list == null ? 0 : list.Count;
            return View(stateModel);
        }
        [HttpPost]
        //public JsonResult GetListByUserId(GridPager pager, string queryStr)
        //{
        //    string userid = GetUserId();
        //    //List<Flow_FormContentModel> list = formContentBLL.GeExaminetListByUserId(ref pager, queryStr, GetUserId()); 
        //    List<Flow_FormContentModel> list = formContentBLL.GetMyExaminetListByUserId(ref pager, queryStr, userid);
        //    var json = new
        //    {
        //        total = pager.totalRows,
        //        rows = (from r in list
        //                select new Flow_FormContentModel()
        //                { 
        //                    Id = r.Id,
        //                    Title = r.Title,
        //                    UserId = r.UserId,
        //                    UserName = r.UserName,
        //                    FormId = r.FormId,
        //                    FormLevel = r.FormLevel,
        //                    CreateTime = r.CreateTime,
        //                    TimeOut = r.TimeOut,
        //                    CurrentStep = formContentBLL.GetCurrentFormStep(r),
        //                    CurrentState = formContentBLL.GetCurrentFormState(r),
        //                    IsExternal = r.IsExternal,
        //                    IsCheck = !(r.CustomMember != null && r.CustomMember.Contains(userid)),
        //                    ExternalURL = r.ExternalURL
        //                }).ToArray()

        //    };
        //    return Json(json);
        //}
        public JsonResult GetListByUserId(GridPager pager, string queryStr, int statetype = 0)
        {
            string userid = GetUserId(); 
            List<V_FLOW_STEPINFOModel> list = formContentBLL.GetMyExaminetListByUserId(ref pager, queryStr, userid, statetype);
            var json = new
            {
                total = pager.totalRows,
                rows = (from r in list
                        select new Flow_FormContentModel()
                        {
                            Id = r.ID,
                            Title = r.TITLE,
                            UserId = r.USERID,
                            FormId = r.FORMID,
                            FormLevel = r.FORMLEVEL,
                            CreateTime = r.CREATETIME,
                            TimeOut = r.TIMEOUT,
                            CurrentStep = formContentBLL.GetCurFormStep(r.ID),
                            CurrentState = formContentBLL.GetCurFormState(r),
                            //UserName = r.USERNAME,  
                            //IsExternal = r.IsExternal,custommember
                            IsCheck = !(r.CUSTOMMEMBER != null && r.CUSTOMMEMBER.Contains(userid)),
                            //ExternalURL = r.ExternalURL
                        }).ToArray()

            };
            return Json(json);
        }


        #region 详细
        [SupportFilter(ActionName = "Details")]
        public ActionResult Details(string id, string contentId)
        {

            Flow_FormModel flowFormModel = formBLL.GetById(id);
            //Flow_FormContentModel centent = formContentBLL.GetById(contentId);
            //var currentStepCheck = stepCheckBLL.GetList(ref GridPager.NotPage, p => p.ContentId == contentId && p.State == 2); //formContentBLL.GetCurrentFormStep(centent);
            //string curStepId = currentStepCheck == null ? "" : currentStepCheck.StepId;
            flowFormModel.stepcheckList = new List<Flow_FormContentStepCheckModel>();
            //获取流程模板的流程步骤
            //flowFormModel.stepList = stepBLL.GetList(ref setNoPagerAscById, flowFormModel.Id);
            List<Flow_StepModel> stepItem = stepBLL.GetList(ref setNoPagerAscById, flowFormModel.Id).OrderBy(a => a.Sort).ToList();
            //获取当前审批信息的流程步骤
            flowFormModel.stepcheckList = stepCheckBLL.GetList(ref GridPager.NotPage, a => a.ContentId == contentId && a.StepId != "00").OrderBy(a => a.CreateTime).ToList();
            //bool iscurrent = false;

            flowFormModel.StartStep = new Flow_StepModel();
            flowFormModel.StartStep.stepCheckStateList = stepCheckStateBLL.GetListByFormIdAndStepID("00", contentId);
            var startStepCheck = stepCheckBLL.GetItem(p => p.ContentId == contentId && p.StepId == "00");
            if (startStepCheck != null && startStepCheck.State == 2)
            {
                flowFormModel.StartStep.stepCheckStateList[0].UserName = "<span class='label label-red'>" + flowFormModel.StartStep.stepCheckStateList[0].UserName + "</span>";
            }
            else
            {
                flowFormModel.StartStep.stepCheckStateList[0].UserName = "<span class='label label-green'>" + flowFormModel.StartStep.stepCheckStateList[0].UserName + "</span>";
            }

            for (int i = 0; i < flowFormModel.stepcheckList.Count; i++)//获取实际步骤下面的步骤规则
            {
                Flow_StepModel item = stepItem.Find(a => a.Id == flowFormModel.stepcheckList[i].StepId);
                flowFormModel.stepcheckList[i].stepModel = item;
                flowFormModel.stepcheckList[i].stepModel.Name = item.Name;//stepname.Contains("<span") ? stepname.Replace("red", "green") : "<span class='label label-green'>" + stepname + "</span>";
                flowFormModel.stepcheckList[i].stepRuleList = GetStepRuleListByStepId(flowFormModel.stepcheckList[i].stepModel.Id);
                //if (flowFormModel.stepcheckList[i].StepId == curStepId && flowFormModel.stepcheckList[i].State == 2)
                //{
                //    iscurrent = true;
                //    flowFormModel.stepcheckList[i].stepModel.Name = stepname.Contains("<span") ? stepname.Replace("green", "red") : "<span class='label label-red'>" + stepname + "</span>";
                //}
                flowFormModel.stepcheckList[i].stepCheckStateList = new List<Flow_FormContentStepCheckStateModel>();
                flowFormModel.stepcheckList[i].stepCheckStateList = stepCheckStateBLL.GetListByStepCheckId(ref GridPager.NotPage, flowFormModel.stepcheckList[i].Id);
            }
            if (!flowFormModel.stepcheckList[flowFormModel.stepcheckList.Count - 1].StateFlag)
            {
                Flow_StepModel sitem = stepItem.Find(a => a.Id == flowFormModel.stepcheckList[flowFormModel.stepcheckList.Count - 1].StepId);
                decimal count = stepItem.Count - sitem.Sort;
                if (sitem.Sort != stepItem.Count && count > 0)
                {
                    for (int j = 0; j < count; j++)
                    {
                        Flow_StepModel model = stepItem[j + sitem.Sort];//.Find(a => a.Sort == sitem.Sort + 1 + j);
                        Flow_FormContentStepCheckModel item = new Flow_FormContentStepCheckModel();
                        item.Id = ResultHelper.NewId;
                        item.stepModel = model;
                        item.stepModel.Name = model.Name;//.Replace("green", "white").Replace("red", "white");
                        item.stepRuleList = GetStepRuleListByStepId(item.stepModel.Id);
                        item.stepCheckStateList = new List<Flow_FormContentStepCheckStateModel>();
                        flowFormModel.stepcheckList.Add(item);
                    }
                }
            }
            return View(flowFormModel);
        }
        //获取步骤下面的规则
        private List<Flow_StepRuleModel> GetStepRuleListByStepId(string stepId)
        {
            List<Flow_StepRuleModel> list = stepRuleBLL.GetList(stepId);
            return list;
        }
        #endregion

        [SupportFilter]
        public ActionResult Edit(string formId, string id)
        {
            //获得当前步骤ID
            string currentStepId = formContentBLL.GetCurrentStepCheckId(formId, id);
            
            Flow_FormModel formModel = formBLL.GetById(formId);
            //是否已经设置布局
            if (!string.IsNullOrEmpty(formModel.HtmlForm))
            {
                ViewBag.Html = formModel.HtmlForm;
            }
            else
            {
                ViewBag.Html = ExceHtmlJs(formId);
            }
            ViewBag.StepCheckMes = formContentBLL.GetCurrentStepCheckMes(ref setNoPagerAscById, formId, id, GetUserId());
            //获取可审批步骤的人
            List<Flow_FormContentStepCheckStateModel> stepCheckStateModel = stepCheckStateBLL.GetListByStepCheckId(ref setNoPagerAscById, currentStepId);
            //决定是否显示审批框
            string currentUser = GetUserId();
            if (stepCheckStateModel.Where(a => a.UserId == currentUser).Count() == 0)
            {
                ViewBag.StepCheckId = "";
            }
            else
            {
                ViewBag.StepCheckId = currentStepId;
            }


            ViewBag.IsCustomMember = false;

            if(!string.IsNullOrEmpty(currentStepId))
            { 
                List<Flow_FormContentStepCheckModel> stepCheckModelList = stepCheckBLL.GetListByFormId(formId,id);
                int j = 0;//下一个步骤
                for (int i = 0; i < stepCheckModelList.Count(); i++)
                {
                    if (currentStepId == stepCheckModelList[i].Id)
                    {
                        j = i;
                    }
                }
                //获得下个步骤
                if (j + 1 < stepCheckModelList.Count())
                { 
                    //查询第二步是否是自选
                    Flow_FormContentStepCheckModel stepModel = stepCheckModelList[j + 1];
                    if (stepModel.IsCustom)
                    {
                        ViewBag.IsCustomMember = true;
                    }

                }
            }
            Flow_FormContentModel model = formContentBLL.GetById(id);
            return View(model);
        }
        //批阅
        [HttpPost]
        [SupportFilter]
        public JsonResult Edit(string Remark, string TheSeal, string FormId, int Flag, string ContentId,string UserList)
        {
            string stepCheckId = formContentBLL.GetCurrentStepCheckId(FormId, ContentId);
            if (stepCheckId == "")
            {
                return Json(JsonHandler.CreateMessage(0, Resource.EditFail));
            }
            string currentUser = GetUserId();
            List<Flow_FormContentStepCheckStateModel> stepCheckStateModelList = stepCheckStateBLL.GetListByStepCheckId(ref setNoPagerAscById, stepCheckId);
            Flow_FormContentStepCheckStateModel stepCheckStateModel = stepCheckStateModelList.SingleOrDefault(a => a.UserId == currentUser);
            //决定是否显示审批框
            if (stepCheckStateModel == null)
            {
                return Json(JsonHandler.CreateMessage(0, "越权操作！"));
            }
            stepCheckStateModel.Reamrk = Remark;
            stepCheckStateModel.TheSeal = TheSeal;
            stepCheckStateModel.CheckFlag = Flag;
            if (stepCheckStateBLL.Edit(ref errors, stepCheckStateModel))
            {
                //获取当前步骤
                Flow_FormContentStepCheckModel stepCheckModel = stepCheckBLL.GetById(stepCheckStateModel.StepCheckId);
                //获得当前的步骤模板
                Flow_StepModel currentStepModel = stepBLL.GetById(stepCheckModel.StepId);
                //驳回直接终止审批
                if(Flag==(int)FlowStateEnum.Reject)
                {
                    stepCheckModel.State = Flag;
                    stepCheckModel.StateFlag = false;
                    stepCheckBLL.Edit(ref errors, stepCheckModel);
                    //重置所有步骤的状态
                    stepCheckBLL.ResetCheckStateByFormCententId(stepCheckModel.Id, ContentId, (int)FlowStateEnum.Progress, (int)FlowStateEnum.Progress);
                    LogHandler.WriteServiceLog(GetUserId(), "Id" + stepCheckStateModel.Id + ",StepCheckId" + stepCheckStateModel.Reamrk, "成功", "修改", "Flow_FormContentStepCheckState");
                    return Json(JsonHandler.CreateMessage(1, Resource.CheckSucceed));
                }
                else if (currentStepModel.IsAllCheck)
                {
                    //启用会签
                    //获得同步骤的同批审批人
                    List<Flow_FormContentStepCheckStateModel> stepCheckStateList = stepCheckStateBLL.GetListByStepCheckId(ref setNoPagerAscById, stepCheckStateModel.StepCheckId);
                    //查看自己是否是最后一个审批人
                    bool complete = stepCheckStateList.Where(a => a.CheckFlag == (int)FlowStateEnum.Progress).Count() == 0;
                    if (complete)
                    {
                        stepCheckModel.State = Flag;
                        stepCheckModel.StateFlag = true;
                        stepCheckBLL.Edit(ref errors, stepCheckModel);
                    }
                    else {
                        //让审批人继续执行这个步骤直到完成
                        LogHandler.WriteServiceLog(GetUserId(), "Id" + stepCheckStateModel.Id + ",StepCheckId" + stepCheckStateModel.Reamrk, "成功", "修改", "Flow_FormContentStepCheckState");
                        return Json(JsonHandler.CreateMessage(1, Resource.CheckSucceed));
                    }
                }
                else
                {
                    //不是会签，任何一个审批都通过
                    stepCheckModel.State = Flag;
                    stepCheckModel.StateFlag = true;
                    stepCheckBLL.Edit(ref errors, stepCheckModel);
                }

                int state = 1;
                //查看下一步是否为自创建
                if (!stepCheckModel.IsEnd && !string.IsNullOrEmpty(UserList))
                {
                    List<Flow_FormContentStepCheckModel> stepCheckList = stepCheckBLL.GetListByFormId(FormId, ContentId);
                    int j = 0;
                    for (int i = stepCheckList.Count() - 1; i >= 0; i--)
                    {
                        if (stepCheckId == stepCheckList[i].Id)
                        {
                            j = i;
                        }
                    }
                    //查看是否还有下一步步骤
                    if(j-1<=stepCheckList.Count())
                    {
                        //查有第二步骤，查看是否是自选
                        Flow_StepModel stepModel = stepBLL.GetById(stepCheckList[j + 1].StepId);
                        if (stepModel.FlowRule==(int)FlowRuleEnum.Customer)
                        {
                            foreach (string userId in UserList.Split(','))
                            {
                                //批量建立步骤审批人表
                                CreateCheckState(stepCheckList[j + 1].Id, userId);
                            }
                        }
                        else {
                            //批量建立审批人员表
                            foreach (string userId in GetStepCheckMemberList(stepCheckList[j + 1].StepId))
                            {
                                //批量建立步骤审批人表
                                CreateCheckState(stepCheckList[j + 1].Id, userId);
                            }
                        }

                    }
                    else
                    {
                        state = 2; //流程结束
                    }
                    
                } 
                LogHandler.WriteServiceLog(GetUserId(), "Id" + stepCheckStateModel.Id + ",StepCheckId" + stepCheckStateModel.Reamrk, "成功", "修改", "Flow_FormContentStepCheckState");
                return Json(JsonHandler.CreateMessage(state, Resource.CheckSucceed));
            }
            else
            {
                string ErrorCol = errors.Error;
                LogHandler.WriteServiceLog(GetUserId(), "Id" + stepCheckStateModel.Id + ",StepCheckId" + stepCheckStateModel.Reamrk + "," + ErrorCol, "失败", "修改", "Flow_FormContentStepCheckState");
                return Json(JsonHandler.CreateMessage(0, Resource.CheckFail + ErrorCol));
            }

        }


        //[SupportFilter(ActionName ="Edit")]
        public ActionResult EditExternal(string formId, string id, int optype = 2)
        {
            ViewBag.StepCheckId = "";
            ViewBag.IsStartStep = false;
            //获得当前步骤ID
            var curStepCheck = stepCheckBLL.GetList(ref GridPager.NotPage, p => p.ContentId == id && p.State == 2);
            if (curStepCheck != null)
            {
                if (optype < 3)
                {
                    if (curStepCheck[0].StepId == "00")
                    {
                        optype = 1; //进入编辑状态
                        ViewBag.IsStartStep = true;//进入起草状态
                    }

                    string ids = string.Join(",", curStepCheck.Select(a => a.Id).ToArray());
                    //获取可审批步骤的人
                    List<Flow_FormContentStepCheckStateModel> stepCheckStateModel = stepCheckStateBLL.GetListByStepCheckIds(ref setNoPagerAscById, ids);
                    //决定是否显示审批框
                    string currentUser = GetUserId();
                    if (stepCheckStateModel.Where(a => a.UserId == currentUser && a.CheckFlag > 1).Count() > 0)
                    {
                        ViewBag.StepCheckId = curStepCheck[0].Id;
                    }
                }
                else
                {
                    optype = 2;
                }
            }
            else
            {
                optype = 2;
            }

            Flow_FormContentModel model = formContentBLL.GetById(id);
            if (model == null)
            {
                model = new Flow_FormContentModel();
                model.FormLevel = "1";
                model.Id = id;
                model.FormId = formId;
            }
            Flow_FormModel formModel = formBLL.GetById(string.IsNullOrEmpty(model.FormId) ? formId : model.FormId);
            model.ExternalURL = formModel.ExternalURL;

            ViewBag.Html = formModel.ExternalURL.Split(',')[optype];

            return View(model);
        }
        //批阅
        [HttpPost]
        //[SupportFilter(ActionName = "Edit")]
        public JsonResult EditExternal(string Remark, string TheSeal, string FormId, int Flag, string ContentId, string UserList,string NextStepId)
        {
            //获取当前步骤实例
            var stepCheckModel = stepCheckBLL.GetItem(p => p.ContentId == ContentId && p.State == 2);
            string stepCheckId = stepCheckModel.Id; //formContentBLL.GetCurrentStepCheckId(FormId, ContentId);
            if (stepCheckId == "")
            {
                return Json(JsonHandler.CreateMessage(0, Resource.EditFail));
            }

            //判断是否越权
            string currentUser = GetUserId();
            List<Flow_FormContentStepCheckStateModel> stepCheckStateModelList = stepCheckStateBLL.GetListByStepCheckId(ref setNoPagerAscById, stepCheckId);
            Flow_FormContentStepCheckStateModel stepCheckStateModel = stepCheckStateModelList.SingleOrDefault(a => a.UserId == currentUser && a.CheckFlag > 1);
            if (stepCheckStateModel == null)
            {
                return Json(JsonHandler.CreateMessage(0, "越权操作！"));
            }

            //获得当前流程实例
            var formcontent = formContentBLL.GetById(ContentId);

            //判断是否终止流程
            if (Flag == (int)FlowStateEnum.Closed)
            {
                var flowForm = formBLL.GetListByTypeId("70000"); //BusinessType.ExaminationReport
                if (flowForm.Count() <= 0 && formcontent.FormId == flowForm[0].Id)
                {
                    return Json(JsonHandler.CreateMessage(0, "没有配置化验审批流程"));
                }
                //终止流程
                stepCheckModel.State = 0;//未通过
                stepCheckModel.StateFlag = true;
                stepCheckBLL.Edit(ref errors, stepCheckModel);

                //更新任务状态
                stepCheckStateModel.Reamrk = "终止,"+ Remark;
                stepCheckStateModel.TheSeal = TheSeal;
                stepCheckStateModel.CheckFlag = 0;
                stepCheckStateModel.CreateTime = System.DateTime.Now;
                stepCheckStateBLL.Edit(ref errors, stepCheckStateModel);

                if (formcontent.FormId == flowForm[0].Id)
                {
                    //Flow_FormContentStepCheckModel rejectstepCheckModel = stepCheckBLL.GetList(ref GridPager.NotPage, p => p.StepId == NextStepId && p.ContentId == stepCheckModel.ContentId).FirstOrDefault();
                   
                    m_testdataBLL.DELETE_LMS_AUDITDATA(ref errors, formcontent.Id);
                }
                //更新表单当前审批人 
                formcontent.CustomMember = "";
                formcontent.AttrY = ResultHelper.NewId;//防同一个用户审批数据没有改变
                formContentBLL.Edit(ref errors, formcontent);
                return Json(JsonHandler.CreateMessage(1, Resource.CheckSucceed));
            }

            if (string.IsNullOrEmpty(NextStepId))
            {
                return Json(JsonHandler.CreateMessage(0, "下一步骤为空"));
            }


            //更新任务状态
            stepCheckStateModel.Reamrk = (Remark=="同意" && stepCheckModel.StepId == "00")?"申请": Remark;
            stepCheckStateModel.TheSeal = TheSeal;
            stepCheckStateModel.CheckFlag = Flag; 
            stepCheckStateModel.CreateTime = System.DateTime.Now;
            if (stepCheckStateBLL.Edit(ref errors, stepCheckStateModel))
            {
                //获得当前的步骤模板
                Flow_StepModel currentStepModel = new Flow_StepModel();
                //判断当前步骤是否为起草
                if (stepCheckModel.StepId != "00")
                {
                    currentStepModel = stepBLL.GetById(stepCheckModel.StepId);
                }
                //是否为退回
                if (!currentStepModel.IsAllCheck && Flag == (int)FlowStateEnum.Reject)
                {
                    stepCheckModel.State = Flag;
                    stepCheckModel.StateFlag = true;
                    stepCheckBLL.Edit(ref errors, stepCheckModel);


                    //下一步数据
                    if (NextStepId == "99")
                    {
                        //更新表单当前审批人 
                        formcontent.CustomMember = "";
                        formcontent.AttrY = ResultHelper.NewId;//防同一个用户审批数据没有改变
                        formContentBLL.Edit(ref errors, formcontent);

                        return Json(JsonHandler.CreateMessage(1, Resource.CheckSucceed));
                    }
                    //新增或更新下一步骤

                    var returnstepmodel = stepBLL.GetById(NextStepId);
                    Flow_FormContentStepCheckModel returnstepCheckModel = stepCheckBLL.GetList(ref GridPager.NotPage, p => p.StepId == NextStepId && p.ContentId == stepCheckModel.ContentId).FirstOrDefault();
                    if (returnstepCheckModel != null)
                    {
                        returnstepCheckModel.State = returnstepCheckModel.StepId == "00" ? 0 : 2;
                        returnstepCheckModel.StateFlag = false;
                        returnstepCheckModel.Id = ResultHelper.NewId;
                        returnstepCheckModel.CreateTime = System.DateTime.Now;
                        stepCheckBLL.Create(ref errors, returnstepCheckModel);
                    }
                    //新增或更新下一步骤任务
                    InsertChecker(ref UserList, returnstepmodel, returnstepCheckModel);

                    //更新表单当前审批人 
                    formcontent.CustomMember = UserList;
                    formcontent.AttrY = ResultHelper.NewId;//防同一个用户审批数据没有改变
                    formContentBLL.Edit(ref errors, formcontent);


                    /*
                    //重置当前任务
                    var stepCheckStatelist = stepCheckStateBLL.GetList(p => p.StepCheckId == stepCheckModel.Id && p.CheckFlag == 2 && p.Id != stepCheckStateModel.Id);
                    foreach (var item in stepCheckStatelist)
                    {
                        item.CheckFlag = Flag;
                        item.Reamrk = "弃权";
                        item.CreateTime = System.DateTime.Now;
                        stepCheckStateBLL.Edit(ref errors, item);
                    }
                    //重置回退步骤状态
                    Flow_FormContentStepCheckModel returnstepCheckModel = stepCheckBLL.GetItem(p=>p.StepId == NextStepId && p.ContentId == stepCheckModel.ContentId); 
                    returnstepCheckModel.State = returnstepCheckModel.StepId == "00" ? 0 : 2;
                    returnstepCheckModel.StateFlag = false;
                    stepCheckBLL.Edit(ref errors, returnstepCheckModel);
                    //重置回退步骤人员状态
                    var returnstepCheckStatelist = stepCheckStateBLL.GetList(p => p.StepCheckId == returnstepCheckModel.Id );
                    foreach (var item in returnstepCheckStatelist)
                    {
                        UserList =string.IsNullOrEmpty(UserList)? item.UserId : UserList + "," + item.UserId;
                        item.CheckFlag = returnstepCheckModel.StepId == "00" ? 0: 2;
                        item.Reamrk = "";
                        item.TheSeal = "";
                        stepCheckStateBLL.Edit(ref errors, item);
                    }

                    //更新表单当前审批人 
                    formcontent.CustomMember = UserList;
                    formcontent.AttrY = ResultHelper.NewId;//防同一个用户审批数据没有改变
                    formContentBLL.Edit(ref errors, formcontent);
                    */

                    LogHandler.WriteServiceLog(GetUserId(), "Id" + stepCheckStateModel.Id + ",StepCheckId" + stepCheckStateModel.Reamrk, "成功", "修改", "Flow_FormContentStepCheckState");
                    return Json(JsonHandler.CreateMessage(1, Resource.CheckSucceed));
                }

                //判断当前步骤是否为起草
                if (stepCheckModel.StepId != "00")
                {
                    //当前的步骤模板
                     currentStepModel = stepBLL.GetById(stepCheckModel.StepId);
                    if (currentStepModel.IsAllCheck)
                    {
                        //启用会签
                        //获得同步骤的同批审批人
                        List<Flow_FormContentStepCheckStateModel> stepCheckStateList = stepCheckStateBLL.GetList(p => p.StepCheckId == stepCheckModel.Id);//stepCheckStateBLL.GetListByStepCheckId(ref setNoPagerAscById, stepCheckStateModel.StepCheckId);
                                                                                                                                                          //查看自己是否是最后一个审批人
                        bool complete = stepCheckStateList.Where(a => a.CheckFlag == (int)FlowStateEnum.Progress).Count() == 0;
                        if (complete)
                        {
                            stepCheckModel.State = 1;
                            stepCheckModel.StateFlag = true;
                            stepCheckBLL.Edit(ref errors, stepCheckModel);
                        }
                        else
                        {
                            
                            //更新表单当前审批人 
                            formcontent.CustomMember =   formcontent.CustomMember.Replace(currentUser, "");
                            formcontent.AttrY = ResultHelper.NewId;//防同一个用户审批数据没有改变
                            formContentBLL.Edit(ref errors, formcontent);

                            //让审批人继续执行这个步骤直到完成
                            LogHandler.WriteServiceLog(GetUserId(), "Id" + stepCheckStateModel.Id + ",StepCheckId" + stepCheckStateModel.Reamrk, "成功", "修改", "Flow_FormContentStepCheckState");
                            return Json(JsonHandler.CreateMessage(1, Resource.CheckSucceed));
                        }
                    }
                    else
                    {
                        //不是会签，任何一个任务都通过
                        var stepCheckStatelist = stepCheckStateBLL.GetList(p => p.StepCheckId == stepCheckModel.Id && p.Id != stepCheckStateModel.Id);
                        foreach (var item in stepCheckStatelist)
                        {
                            item.CheckFlag = 1;//通过
                            item.Reamrk = "弃权";
                            item.CreateTime = System.DateTime.Now;
                            stepCheckStateBLL.Edit(ref errors, item);
                        }

                        stepCheckModel.State = 1;
                        stepCheckModel.StateFlag = true;
                        stepCheckBLL.Edit(ref errors, stepCheckModel);
                    }
                }
                else
                {
                    stepCheckModel.State = 1;
                    stepCheckModel.StateFlag = true;
                    stepCheckBLL.Edit(ref errors, stepCheckModel);

                    //删除历史数据
                    stepCheckBLL.Deletes(ref errors, p => p.ContentId == ContentId && p.STEPNO > stepCheckModel.STEPNO);
                }
                 

                //下一步数据
                if (NextStepId == "99")
                {
                    //更新表单当前审批人 
                    formcontent.CustomMember = "";
                    formcontent.AttrY = ResultHelper.NewId;//防同一个用户审批数据没有改变
                    formContentBLL.Edit(ref errors, formcontent);

                    return Json(JsonHandler.CreateMessage(1, Resource.CheckSucceed));
                }
                //新增或更新下一步骤
                var nextstepmodel = stepBLL.GetById(NextStepId);
                var nextstepcheckmodel = stepCheckBLL.GetList(ref GridPager.NotPage, p=>p.StepId == NextStepId && p.ContentId == stepCheckModel.ContentId).FirstOrDefault();
                
                //if(nextstepcheckmodel == null)
                //{
                    nextstepcheckmodel = new Flow_FormContentStepCheckModel();
                    nextstepcheckmodel.StepId = NextStepId;
                    nextstepcheckmodel.ContentId = stepCheckModel.ContentId;
                    nextstepcheckmodel.Id = ResultHelper.NewId;
                    nextstepcheckmodel.IsCustom = !string.IsNullOrEmpty(UserList);
                    nextstepcheckmodel.IsEnd = false; 
                    nextstepcheckmodel.STEPNO = nextstepmodel.Sort;
                    nextstepcheckmodel.CreateTime = System.DateTime.Now;
                    nextstepcheckmodel.State = 2;
                    stepCheckBLL.Create(ref errors, nextstepcheckmodel);

                //}
                //else
                //{
                //    nextstepcheckmodel.CreateTime = System.DateTime.Now;
                //    nextstepcheckmodel.State = 2;
                //    stepCheckBLL.Edit(ref errors, nextstepcheckmodel); 
                //} 
                //新增或更新下一步骤任务
                InsertChecker(ref UserList, nextstepmodel, nextstepcheckmodel);

                //更新表单当前审批人 
                formcontent.CustomMember = UserList;
                formcontent.AttrY = ResultHelper.NewId;//防同一个用户审批数据没有改变
                formContentBLL.Edit(ref errors, formcontent);

                //查看下一步是否为自创建
                //if (!stepCheckModel.IsEnd && !string.IsNullOrEmpty(UserList))
                //{
                //    List<Flow_FormContentStepCheckModel> stepCheckList = stepCheckBLL.GetListByFormId(FormId, ContentId);
                //    int j = 0;
                //    for (int i = stepCheckList.Count() - 1; i >= 0; i--)
                //    {
                //        if (stepCheckId == stepCheckList[i].Id)
                //        {
                //            j = i;
                //        }
                //    }
                //    //查看是否还有下一步步骤
                //    if (j + 1 < stepCheckList.Count())
                //    {
                //        //查有第二步骤，查看是否是自选
                //        Flow_StepModel stepModel = stepBLL.GetById(stepCheckList[j + 1].StepId);
                //        if (stepModel.FlowRule == (int)FlowRuleEnum.Customer)
                //        {
                //            foreach (string userId in UserList.Split(','))
                //            {
                //                //批量建立步骤审批人表
                //                CreateCheckState(stepCheckList[j + 1].Id, userId);
                //            }
                //        }
                //        else
                //        {
                //            //批量建立审批人员表
                //            foreach (string userId in GetStepCheckMemberList(stepCheckList[j + 1].StepId))
                //            {
                //                //批量建立步骤审批人表
                //                CreateCheckState(stepCheckList[j + 1].Id, userId);
                //            }
                //        }

                //    } 
                //}

                LogHandler.WriteServiceLog(GetUserId(), "Id" + stepCheckStateModel.Id + ",StepCheckId" + stepCheckStateModel.Reamrk, "成功", "修改", "Flow_FormContentStepCheckState");
                return Json(JsonHandler.CreateMessage(1, Resource.CheckSucceed));
            }
            else
            {
                string ErrorCol = errors.Error;
                LogHandler.WriteServiceLog(GetUserId(), "Id" + stepCheckStateModel.Id + ",StepCheckId" + stepCheckStateModel.Reamrk + "," + ErrorCol, "失败", "修改", "Flow_FormContentStepCheckState");
                return Json(JsonHandler.CreateMessage(0, Resource.CheckFail + ErrorCol));
            }

        }

        private void InsertChecker(ref string userlist, Flow_StepModel stepModel, Flow_FormContentStepCheckModel stepCheckModel)
        {
            //获得流转规则下的审批人员
            List<string> userIdList = new List<string>();
            if (stepModel.FlowRule == (int)FlowRuleEnum.Customer)
            {
                string[] arrUserList = userlist.Split(',');
                foreach (string s in arrUserList)
                {
                    userIdList.Add(s);
                }
            }
            else
            {
                userIdList = GetStepCheckMemberList(stepModel.Id, stepCheckModel.ContentId);
                userlist = string.Join(",", userIdList.ToArray());
            }

            for (int j = 0; j < userIdList.Count(); j++)
            {
                string userid = userIdList[j];
                Flow_FormContentStepCheckStateModel stepCheckModelState = stepCheckStateBLL.GetItem(p=>p.StepCheckId == stepCheckModel.Id && p.UserId == userid);
                if (stepCheckModelState == null)
                {
                    //批量建立步骤审批人表 
                    stepCheckModelState = new Flow_FormContentStepCheckStateModel();
                    stepCheckModelState.Id = ResultHelper.NewId;
                    stepCheckModelState.StepCheckId = stepCheckModel.Id;
                    stepCheckModelState.UserId = userIdList[j];
                    stepCheckModelState.CheckFlag = 2;
                    stepCheckModelState.Reamrk = "";
                    stepCheckModelState.TheSeal = "";
                    stepCheckModelState.CreateTime = ResultHelper.NowTime;
                    stepCheckStateBLL.Create(ref errors, stepCheckModelState);
                }
                else
                {
                    stepCheckModelState.CheckFlag = 2;
                    stepCheckModelState.Reamrk = "";
                    stepCheckModelState.TheSeal = "";
                    stepCheckModelState.CreateTime = ResultHelper.NowTime;
                    stepCheckStateBLL.Edit(ref errors, stepCheckModelState);
                }
            }
        }

        //获取步骤审批人
        public List<string> GetStepCheckMemberList(string stepId, string formContentId)
        {
            List<string> userModelList = new List<string>();
            Flow_StepModel model = stepBLL.GetById(stepId);
            if (model.FlowRule == (int)FlowRuleEnum.Lead)
            {
                SysUserModel userModel = userBLL.GetById(GetUserId());
                string[] array = userModel.Lead.Split(',');//获得领导，可能有多个领导
                foreach (string str in array)
                {
                    userModelList.Add(str);
                }
            }
            else if (model.FlowRule == (int)FlowRuleEnum.Position)
            {
                string[] array = model.Execution.Split(',');//获得领导，可能有多个领导
                foreach (string str in array)
                {
                    List<SysUserModel> userList = userBLL.GetListByPosId(str);
                    foreach (SysUserModel userModel in userList)
                    {
                        userModelList.Add(userModel.Id);
                    }
                }
            }
            else if (model.FlowRule == (int)FlowRuleEnum.Department)
            {
                GridPager pager = new GridPager()
                {
                    rows = 10000,
                    page = 1,
                    sort = "Id",
                    order = "desc"
                };
                string[] array = model.Execution.Split(',');
                foreach (string str in array)
                {
                    List<SysUserModel> userList = userBLL.GetUserByDepId(ref pager, str, "");
                    foreach (SysUserModel userModel in userList)
                    {
                        userModelList.Add(userModel.Id);
                    }
                }
            }
            else if (model.FlowRule == (int)FlowRuleEnum.Person)
            {
                string[] array = model.Execution.Split(',');//获得自选人员，可能有多个人员
                foreach (string str in array)
                {
                    userModelList.Add(str);
                }
            }
            else if (model.FlowRule == (int)FlowRuleEnum.Customer)
            {
                string users = formContentBLL.GetById(formContentId).CustomMember;
                string[] array = users.Split(',');//获得领导，可能有多个领导
                foreach (string str in array)
                {
                    userModelList.Add(str);
                }
            }
            return userModelList;
        }


        #region 下一步操作
        //curStepId为空，则contentId为提交申请操作，不为空，则为审批流程操作
        public ActionResult StepLookUp(string contentId,string curStepId, string optype,string externalurl="")
        {
            ViewBag.ContentId = contentId;
            ViewBag.CurStepId = curStepId;
            ViewBag.Optype = optype;
            ViewBag.ExternalUrl = externalurl;
            return View();
        }


        //curStepId为空，则contentId为提交申请操作，不为空，则为审批流程操作
        [HttpPost]
        public JsonResult GetStepList(GridPager pager, string contentId, string curStepId, string optype, string externalurl = "")
        {
            List<Flow_StepModel> list;
            Flow_StepModel stepmodel=new Flow_StepModel();
            Flow_FormContentStepCheckModel stepcheck=new Flow_FormContentStepCheckModel();
            stepmodel.IsAllCheck = false;
            if (!string.IsNullOrEmpty(curStepId))
            {
                stepcheck = stepCheckBLL.GetById(curStepId);
                if (stepcheck.StepId != "00")
                {
                    stepmodel = stepBLL.GetById(stepcheck.StepId);
                }
            }
            if(stepmodel.IsAllCheck||optype == "1")
            {
                //同意　
                list = new List<Flow_StepModel>();
                if (string.IsNullOrEmpty(curStepId) && !string.IsNullOrEmpty(contentId))
                {
                    //获取当前的Form流程模版 即：flow_form
                    Flow_FormModel formModel = formBLL.GetByExternalURL(externalurl);
                    if (formModel == null) return Json(JsonHandler.CreateMessage(0, Resource.EditFail + "，未找到流程模板"));

                    //获取当前流程的步骤 即：flow_step
                    //判断是否自行指定审批人
                    List<Flow_StepModel> flowStep = stepBLL.GetList(ref setNoPagerAscBySort, formModel.Id);
                    if (flowStep.Count() <= 0) return Json(JsonHandler.CreateMessage(0, Resource.EditFail + "，流程模板没有配置相关步骤"));
                    Flow_StepModel step = flowStep.Where(a => a.Sort == 1).ToList()[0];
                    list.Add(step);
                }
                if (!string.IsNullOrEmpty(curStepId) && !string.IsNullOrEmpty(contentId))
                {
                    //if (stepcheck.StepId != "00")
                    //{
                    //    var step = stepBLL.GetById(stepcheck.StepId);

                    //    //获得步骤对应的规则
                    //    List<Flow_StepRuleModel> stepRuleModelList = stepRuleBLL.GetList(step.Id);
                    //    //获取规则判断流转方向
                    //    foreach (Flow_StepRuleModel stepRuleModel in stepRuleModelList)
                    //    {
                    //        //如果符合规则，判断是否还有下一步
                    //        if (stepRuleModel.NextStep != "0")
                    //        {
                    //            stepmodel = stepBLL.GetById(stepRuleModel.NextStep);
                    //            list.Add(stepmodel);
                    //        }
                    //        else
                    //        {
                    //            stepmodel = new Flow_StepModel();
                    //            stepmodel.Id = "99";
                    //            stepmodel.Name = "审批结束";
                    //            stepmodel.ExecutionName = "申请人";
                    //            stepmodel.StepNo = "结束";
                    //            stepmodel.FlowRule = 6;
                    //            stepmodel.IsAllCheck = false;
                    //            stepmodel.IsCustom = false;
                    //            stepmodel.Sort = 99;
                    //            list.Add(stepmodel);
                    //        }
                    //    }
                    //}

                    var formcontent = formContentBLL.GetById(contentId);
                    //顺序下一步
                    stepmodel = stepBLL.GetNextStepByCurStepId(stepcheck.StepId == "00" ? "" : stepcheck.StepId, formcontent.FormId);
                    if (stepmodel == null)
                    {
                        //流程结束
                        stepmodel = new Flow_StepModel();
                        stepmodel.Id = "99";
                        stepmodel.Name = "审批结束";
                        stepmodel.ExecutionName = "申请人";
                        stepmodel.StepNo = "结束";
                        stepmodel.FlowRule = 6;
                        stepmodel.IsAllCheck = false;
                        stepmodel.IsCustom = false;
                        stepmodel.Sort = 99;
                    }
                    list.Add(stepmodel);
                }
            }
            else
            {
                //退回 
                list = stepBLL.GetHisStepBycontentId(contentId).GroupBy(p => p.Id).Select(q => q.First()).ToList();
                var startusername = stepBLL.GetFirstStepUserName(contentId);
                //流程起草
                var stepmodel1 = new Flow_StepModel();
                stepmodel1.Id = "00";
                stepmodel1.Name = "流程起草";
                stepmodel1.Execution = startusername;
                stepmodel1.ExecutionName = startusername;
                stepmodel1.StepNo = "开始";
                stepmodel1.FlowRule = 6;
                stepmodel1.IsCustom = false;
                stepmodel1.Sort = 0;
                stepmodel1.IsAllCheck = false;
                list.Add(stepmodel1);
            }

            GridRows<Flow_StepModel> grs = new GridRows<Flow_StepModel>();
            grs.rows = list;
            grs.total = 1000;
            return Json(grs);
        }


        #endregion

        //创建审批人
        private void CreateCheckState(string stepCheckId, string userId)
        {
            Flow_FormContentStepCheckStateModel stepCheckModelState = new Flow_FormContentStepCheckStateModel();
            stepCheckModelState.Id = ResultHelper.NewId;
            stepCheckModelState.StepCheckId = stepCheckId;
            stepCheckModelState.UserId = userId;
            stepCheckModelState.CheckFlag = 2;
            stepCheckModelState.Reamrk = "";
            stepCheckModelState.TheSeal = "";
            stepCheckModelState.CreateTime = ResultHelper.NowTime;
            stepCheckStateBLL.Create(ref errors, stepCheckModelState);
        }
        //获得审批人列表
        private List<string> GetStepCheckMemberList(string stepId)
        {
            List<string> userModelList = new List<string>();
            Flow_StepModel model = stepBLL.GetById(stepId);
            if (model.FlowRule == (int)FlowRuleEnum.Lead)
            {
                SysUserModel userModel = userBLL.GetById(GetUserId());
                string[] array = userModel.Lead.Split(',');//获得领导，可能有多个领导
                foreach (string str in array)
                {
                    userModelList.Add(str);
                }
            }
            else if (model.FlowRule == (int)FlowRuleEnum.Position)
            {
                string[] array = model.Execution.Split(',');//获得领导，可能有多个领导
                foreach (string str in array)
                {
                    List<SysUserModel> userList = userBLL.GetListByPosId(str);
                    foreach (SysUserModel userModel in userList)
                    {
                        userModelList.Add(userModel.Id);
                    }
                }
            }
            else if (model.FlowRule == (int)FlowRuleEnum.Department)
            {
                GridPager pager = new GridPager()
                {
                    rows = 10000,
                    page = 1,
                    sort = "Id",
                    order = "desc"
                };
                string[] array = model.Execution.Split(',');//获得领导，可能有多个领导
                foreach (string str in array)
                {
                    List<SysUserModel> userList = userBLL.GetUserByDepId(ref pager, str, "");
                    foreach (SysUserModel userModel in userList)
                    {
                        userModelList.Add(userModel.Id);
                    }
                }
            }
            else if (model.FlowRule == (int)FlowRuleEnum.Person)
            {
                string[] array = model.Execution.Split(',');//获得领导，可能有多个领导
                foreach (string str in array)
                {
                    userModelList.Add(str);
                }
            }
          
            return userModelList;
        }

        #region 获得表单
        //根据设定公文，生成表单及控制条件
        private string ExceHtmlJs(string id)
        {
            //定义一个sb为生成HTML表单
            StringBuilder sbHtml = new StringBuilder();
            StringBuilder sbJS = new StringBuilder();
            sbJS.Append("<script type='text/javascript'>function CheckForm(){");
            Flow_FormModel model = formBLL.GetById(id);

            #region 判断流程是否有字段,有就生成HTML表单
            sbHtml.Append(JuageExc(model.AttrA, "A", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrB, "B", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrC, "C", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrD, "D", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrE, "E", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrF, "F", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrG, "G", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrH, "H", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrI, "I", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrJ, "J", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrK, "K", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrL, "L", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrM, "M", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrN, "N", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrO, "O", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrP, "P", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrQ, "Q", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrR, "R", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrS, "S", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrT, "T", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrU, "U", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrV, "V", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrW, "W", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrX, "X", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrY, "Y", ref sbJS));
            sbHtml.Append(JuageExc(model.AttrZ, "Z", ref sbJS));
            #endregion
            sbJS.Append("return true}</script>");
            return sbJS.ToString()+sbHtml.ToString();
        }
        //对比
        private bool JudgeVal(string attrId, string rVal, string cVal, string lVal)
        {
            string attrType = formAttrBLL.GetById(attrId).AttrType;
            return new FlowHelper().Judge(attrType, rVal, cVal, lVal);
        }
        private string JuageExc(string attr, string no, ref StringBuilder sbJS)
        {

            if (!string.IsNullOrEmpty(attr))
            {
                return GetHtml(attr, no, ref sbJS);

            }
            return "";
        }
        //获取指定名称的HTML表单
        private string GetHtml(string id, string no, ref StringBuilder sbJS)
        {
            StringBuilder sb = new StringBuilder();
            Flow_FormAttrModel attrModel = formAttrBLL.GetById(id);
            sb.AppendFormat("<tr><td style='width:100px; text-align:right;'>{0} :</td>", attrModel.Title);
            //获取指定类型的HTML表单
            sb.AppendFormat("<td>{0}</td></tr>", new FlowHelper().GetInput(attrModel.AttrType, attrModel.Name, no, attrModel.OptionList,false));
            sbJS.Append(attrModel.CheckJS);
            return sb.ToString();
        }
        #endregion

    }
}
